﻿Imports Crownwood.Magic.Menus
Imports System.Threading
Imports System.Data.SqlClient
Imports System.IO
Imports System.Timers
Imports System.IO.Ports
Imports lablinkhelper
Imports System.Net
Imports System.Net.Sockets

Public Class frmMain
    Inherits Form

#Region "Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call
        'Me.Opacity = 0
        gv_bIncreateOrDecrete = True
    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    Friend WithEvents tbr As System.Windows.Forms.ToolBar
    Friend WithEvents ToolBarButton1 As System.Windows.Forms.ToolBarButton
    Friend WithEvents ToolBarButton2 As System.Windows.Forms.ToolBarButton
    Friend WithEvents ToolBarButton4 As System.Windows.Forms.ToolBarButton
    Friend WithEvents StatusBar1 As System.Windows.Forms.StatusBar
    Friend WithEvents StatusBarPanel1 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents StatusBarPanel2 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents StatusBarPanel3 As System.Windows.Forms.StatusBarPanel
    Public WithEvents PictureBox1 As System.Windows.Forms.PictureBox
    Friend WithEvents imgAdminnistration As System.Windows.Forms.ImageList
    Friend WithEvents ToolBarButton3 As System.Windows.Forms.ToolBarButton
    Friend WithEvents StatusBarPanel4 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents txtLog As Windows.Forms.TextBox
    Friend WithEvents ToolBarButton5 As Windows.Forms.ToolBarButton

    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmMain))
        Me.tbr = New System.Windows.Forms.ToolBar()
        Me.ToolBarButton1 = New System.Windows.Forms.ToolBarButton()
        Me.ToolBarButton2 = New System.Windows.Forms.ToolBarButton()
        Me.ToolBarButton4 = New System.Windows.Forms.ToolBarButton()
        Me.ToolBarButton3 = New System.Windows.Forms.ToolBarButton()
        Me.ToolBarButton5 = New System.Windows.Forms.ToolBarButton()
        Me.imgAdminnistration = New System.Windows.Forms.ImageList(Me.components)
        Me.StatusBar1 = New System.Windows.Forms.StatusBar()
        Me.StatusBarPanel1 = New System.Windows.Forms.StatusBarPanel()
        Me.StatusBarPanel2 = New System.Windows.Forms.StatusBarPanel()
        Me.StatusBarPanel3 = New System.Windows.Forms.StatusBarPanel()
        Me.StatusBarPanel4 = New System.Windows.Forms.StatusBarPanel()
        Me.PictureBox1 = New System.Windows.Forms.PictureBox()
        Me.Timeout = New System.Windows.Forms.Timer(Me.components)
        Me.txtLog = New System.Windows.Forms.TextBox()
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.StatusBarPanel2, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.StatusBarPanel3, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.StatusBarPanel4, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        '
        'tbr
        '
        Me.tbr.Buttons.AddRange(New System.Windows.Forms.ToolBarButton() {Me.ToolBarButton1, Me.ToolBarButton2, Me.ToolBarButton4, Me.ToolBarButton3, Me.ToolBarButton5})
        Me.tbr.DropDownArrows = True
        Me.tbr.ImageList = Me.imgAdminnistration
        Me.tbr.Location = New System.Drawing.Point(0, 0)
        Me.tbr.Name = "tbr"
        Me.tbr.ShowToolTips = True
        Me.tbr.Size = New System.Drawing.Size(869, 28)
        Me.tbr.TabIndex = 1
        Me.tbr.TextAlign = System.Windows.Forms.ToolBarTextAlign.Right
        '
        'ToolBarButton1
        '
        Me.ToolBarButton1.ImageIndex = 0
        Me.ToolBarButton1.Name = "ToolBarButton1"
        Me.ToolBarButton1.Tag = "-1"
        Me.ToolBarButton1.ToolTipText = "Đăng nhập"
        '
        'ToolBarButton2
        '
        Me.ToolBarButton2.ImageIndex = 5
        Me.ToolBarButton2.Name = "ToolBarButton2"
        Me.ToolBarButton2.Tag = "-2"
        Me.ToolBarButton2.ToolTipText = "Thay đổi ngôn ngữ hiển thị"
        '
        'ToolBarButton4
        '
        Me.ToolBarButton4.ImageIndex = 13
        Me.ToolBarButton4.Name = "ToolBarButton4"
        Me.ToolBarButton4.Tag = "-3"
        Me.ToolBarButton4.ToolTipText = "Thoát"
        '
        'ToolBarButton3
        '
        Me.ToolBarButton3.ImageIndex = 8
        Me.ToolBarButton3.Name = "ToolBarButton3"
        Me.ToolBarButton3.Tag = "-4"
        Me.ToolBarButton3.ToolTipText = "Thiết lập lại tham số hệ thống"
        '
        'ToolBarButton5
        '
        Me.ToolBarButton5.ImageIndex = 14
        Me.ToolBarButton5.Name = "ToolBarButton5"
        Me.ToolBarButton5.Tag = "-7"
        '
        'imgAdminnistration
        '
        Me.imgAdminnistration.ImageStream = CType(resources.GetObject("imgAdminnistration.ImageStream"), System.Windows.Forms.ImageListStreamer)
        Me.imgAdminnistration.TransparentColor = System.Drawing.Color.Transparent
        Me.imgAdminnistration.Images.SetKeyName(0, "")
        Me.imgAdminnistration.Images.SetKeyName(1, "")
        Me.imgAdminnistration.Images.SetKeyName(2, "")
        Me.imgAdminnistration.Images.SetKeyName(3, "")
        Me.imgAdminnistration.Images.SetKeyName(4, "")
        Me.imgAdminnistration.Images.SetKeyName(5, "")
        Me.imgAdminnistration.Images.SetKeyName(6, "")
        Me.imgAdminnistration.Images.SetKeyName(7, "")
        Me.imgAdminnistration.Images.SetKeyName(8, "")
        Me.imgAdminnistration.Images.SetKeyName(9, "")
        Me.imgAdminnistration.Images.SetKeyName(10, "")
        Me.imgAdminnistration.Images.SetKeyName(11, "")
        Me.imgAdminnistration.Images.SetKeyName(12, "")
        Me.imgAdminnistration.Images.SetKeyName(13, "")
        Me.imgAdminnistration.Images.SetKeyName(14, "advancedsettings.png")
        '
        'StatusBar1
        '
        Me.StatusBar1.Location = New System.Drawing.Point(0, 556)
        Me.StatusBar1.Name = "StatusBar1"
        Me.StatusBar1.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.StatusBarPanel1, Me.StatusBarPanel2, Me.StatusBarPanel3, Me.StatusBarPanel4})
        Me.StatusBar1.ShowPanels = True
        Me.StatusBar1.Size = New System.Drawing.Size(869, 22)
        Me.StatusBar1.TabIndex = 0
        '
        'StatusBarPanel1
        '
        Me.StatusBarPanel1.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents
        Me.StatusBarPanel1.Icon = CType(resources.GetObject("StatusBarPanel1.Icon"), System.Drawing.Icon)
        Me.StatusBarPanel1.Name = "StatusBarPanel1"
        Me.StatusBarPanel1.Text = "Chi nhánh"
        Me.StatusBarPanel1.Width = 87
        '
        'StatusBarPanel2
        '
        Me.StatusBarPanel2.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring
        Me.StatusBarPanel2.Icon = CType(resources.GetObject("StatusBarPanel2.Icon"), System.Drawing.Icon)
        Me.StatusBarPanel2.Name = "StatusBarPanel2"
        Me.StatusBarPanel2.Text = "Người dùng"
        Me.StatusBarPanel2.Width = 655
        '
        'StatusBarPanel3
        '
        Me.StatusBarPanel3.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents
        Me.StatusBarPanel3.Name = "StatusBarPanel3"
        Me.StatusBarPanel3.Width = 10
        '
        'StatusBarPanel4
        '
        Me.StatusBarPanel4.Alignment = System.Windows.Forms.HorizontalAlignment.Center
        Me.StatusBarPanel4.Icon = CType(resources.GetObject("StatusBarPanel4.Icon"), System.Drawing.Icon)
        Me.StatusBarPanel4.Name = "StatusBarPanel4"
        Me.StatusBarPanel4.Text = "Phiên bản mới"
        Me.StatusBarPanel4.ToolTipText = "Click vào đây để quét phiên bản mới nhất"
        '
        'PictureBox1
        '
        Me.PictureBox1.Dock = System.Windows.Forms.DockStyle.Fill
        Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image)
        Me.PictureBox1.Location = New System.Drawing.Point(0, 28)
        Me.PictureBox1.Name = "PictureBox1"
        Me.PictureBox1.Size = New System.Drawing.Size(869, 528)
        Me.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
        Me.PictureBox1.TabIndex = 5
        Me.PictureBox1.TabStop = False
        '
        'txtLog
        '
        Me.txtLog.BackColor = System.Drawing.Color.White
        Me.txtLog.Font = New System.Drawing.Font("Microsoft Sans Serif", 27.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txtLog.Location = New System.Drawing.Point(0, 34)
        Me.txtLog.Multiline = True
        Me.txtLog.Name = "txtLog"
        Me.txtLog.ReadOnly = True
        Me.txtLog.Size = New System.Drawing.Size(16, 12)
        Me.txtLog.TabIndex = 7
        Me.txtLog.Visible = False
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(869, 578)
        Me.Controls.Add(Me.PictureBox1)
        Me.Controls.Add(Me.txtLog)
        Me.Controls.Add(Me.StatusBar1)
        Me.Controls.Add(Me.tbr)
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.IsMdiContainer = True
        Me.KeyPreview = True
        Me.MinimumSize = New System.Drawing.Size(798, 570)
        Me.Name = "frmMain"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Dynamic Menu"
        Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.StatusBarPanel2, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.StatusBarPanel3, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.StatusBarPanel4, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

#End Region

#Region "Khai báo biến, hằng ..."

    Public _mnuMain As New MenuControl
    Dim _mvOmenu As cls_BuildMenu
    Private ReadOnly _mvArrCtr As New ArrayList
    Dim _tblPortDevice As New DataTable
    ReadOnly _clsDeviceconnection As New clsDeviceConnection

    Private Const MTMax As Byte = &H5A
    'Dim ser As New IO.Ports.SerialPort

    Private Structure ResultDeTail
        Dim Results() As String
    End Structure

    Dim _arrStack() As StackStruct       'Biến của Axsym
    Dim _arrStackCi4100() As StackStruct       'Biến của CI4100
    Dim Stack1650 As StackStruct
    Dim Testof1650 As Byte

    Private Shared bStep() As Byte   'Biến của Centaur, Axsym...
    Private Shared bStep_CA550() As Byte   'Biến của CA550
    Private Shared bStep_AU400() As Byte   'Biến của AU400
    Private Shared bStep_AU640() As Byte   'Biến của AU400
    Private Shared bStep_CI4100() As Byte   'Biến của CI4100

    '------Biến của XT1800
    Private Path_XT1800 As String
    Private bStep_XT1800 As Byte
    Private Result_XT1800 As String
    Private buff_XT1800 As String
    Private blnFinalFrame_XT1800 As Boolean
    Private sIFrame1_XT1800 As String
    Private sIFrame2_XT1800 As String
    Private ResultRecords_XT1800 As ResultDeTail

    '------Biến của XS1000i
    Private Path_XS100i As String
    Private bStep_XS100i As Byte
    Private Result_XS100i As String
    Private buff_XS100i As String
    Private blnFinalFrame_XS100i As Boolean
    Private sIFrame1_XS100i As String
    Private sIFrame2_XS100i As String
    Private ResultRecords_XS100i As ResultDeTail

    '------Biến của Ruby
    Private bStep_Ruby As Byte
    Private Result_Ruby As String
    Private buff_Ruby As String
    Private blnFinalFrame_Ruby As Boolean
    Private sIFrame1_Ruby As String
    Private sIFrame2_Ruby As String
    Private ResultRecords_Ruby As ResultDeTail
    Dim ghostnew As DateTime = New DateTime(2015, 5, 25)
    Dim ghostold As DateTime = DateTime.Now
    '------Biến của CA500
    Private bStep_CA500 As Byte
    Private Result_CA500 As String
    Private buff_CA500 As String
    Private blnFinalFrame_CA500 As Boolean
    Private sIFrame1_CA500 As String
    Private sIFrame2_CA500 As String
    Private ResultRecords_CA500 As ResultDeTail

    Private Result_ADVIA1650() As String
    Private sReq1650 As String

    Friend WithEvents Timeout As Windows.Forms.Timer
    Private Shared blnTimeout As Boolean = False
    Private Shared TimeoutCnt As Byte = 0
    '*********************************
    'COBAS400
    '*********************************
    Private Shared clsCOBAS400 As New COBAS400
    Private Shared ARTIMER As Timers.Timer
    Private Shared COBAS_count As Byte
    '**********************************

    '*********************************
    'COBAS411
    '*********************************


    Private RunWithLablinkService As Boolean

#End Region

#Region "Form Events"

    Private Sub FrmMainLoad(ByVal sender As System.Object, ByVal e As EventArgs) Handles MyBase.Load
        LoadMainFormHandler(sender, e)
    End Sub

    Private Sub LoadMainFormHandler(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Const sNewFormat As String = "dd/MM/yyyy"
            Dim rkey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\International", True)
            rkey.SetValue("sShortDate", sNewFormat)
            rkey.SetValue("sLongDate", sNewFormat)
        Catch ex As Exception
        End Try
        LoadDefaultBackGround()
        txtLog.Dock = DockStyle.Fill
        If LoginSystem(sender, e) Then
            'RunWithLablinkService = False
            'RunWithLablinkService = lablinkhelper.Utilities.GetRunWithLablinkService()
            Try
                'tbr.Buttons.Item(4).Visible = Not RunWithLablinkService
                'VietBaIT.CommonLibrary.Utility.InitSubSonic(lablinkhelper.Utilities.GetDBConnectionString(), "ORM")
                Dim connc = HongNgocITUtilities.Lis.ConnecttoServerforService()
                If (ghostold <= ghostnew) Then
                    lablinkhelper.Utilities.InitSubSonic(connc, "HADK")
                    'VietBaIT.CommonLibrary.Utility.InitSubSonic(connc, "ORM")
                End If


            Catch ex As Exception
            End Try
        Else
            Application.Exit()
        End If
    End Sub

    Private Sub tbr_ButtonClick(ByVal sender As System.Object, ByVal e As Windows.Forms.ToolBarButtonClickEventArgs) Handles tbr.ButtonClick
        Try
            Select Case e.Button.Tag
                Case "-1"
                    LoadMainFormHandler(Me, New EventArgs())

                    'Dim svOFrmLogon As New frmLogin
                    'svOFrmLogon.ShowDialog()
                    ''Nếu người dùng nhấn nút Close
                    'If gv_bReturnHome = True Then
                    'Else
                    _mvArrCtr.Clear()
                    'Xóa tất cả các Control ngoại trừ Toolbar và StatusBar trên Form Main
                    For Each ctr As Control In Controls
                        If ctr.Name.Equals(tbr.Name) Or ctr.Name.Equals(StatusBar1.Name) Or ctr.Name.Equals(PictureBox1.Name) Then
                        Else
                            _mvArrCtr.Add(ctr)
                        End If
                    Next
                    For i As Integer = 0 To _mvArrCtr.Count - 1
                        Controls.Remove(_mvArrCtr(i))
                    Next
                    '************************************************
                    '************************************************
                    RemoveHandler tbr.ButtonClick, AddressOf _ClickTbr
                    Initialize()
                    'Thủ thuật để ko bị lỗi MainMenu ko nhận Focus khi có 1 phân hệ kiểu Docking
                    'WindowState = FormWindowState.Minimized
                    'WindowState = FormWindowState.Maximized
                    'End If

                Case "-2"   'Button Change language
                    If tbr.Buttons(1).Text = "VN" Then
                        tbr.Buttons(1).Text = "EN"
                        gv_sLanguageDisplay = "VN"
                    Else
                        tbr.Buttons(1).Text = "VN"
                        gv_sLanguageDisplay = "EN"
                    End If
                    ChangeLanguage()
                    tbr.Buttons(1).ToolTipText = IIf(gv_sLanguageDisplay.ToUpper.Equals("VN"), "Chuyển sang giao diện Tiếng Anh", "Chuyển sang giao diện Tiếng Việt")
                Case "-3"   'Button Exit
                    LogClose()
                    If RunWithLablinkService Then
                        Application.Exit()
                    Else
                        If MessageBox.Show("Bạn có muốn tắt ứng dụng" + vbCrLf + vbCrLf + "Tắt ứng dụng có thể gây ra lỗi trong quá trình gửi nhận dữ liệu với máy Xét Nhiệm", "Thông báo Tắt ứng dụng", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
                            Application.Exit()
                        End If
                    End If

                Case "-4"
                    Dim frm As New FRM_SetParamSystem
                    frm.ShowDialog()
                Case "-5"
                    Dim frm As New FrmControlRemoteDevice
                    frm.ShowDialog()
                Case "-7"
                    Dim frm As New FrmPortManagement
                    frm.ShowDialog()
            End Select
        Catch ex As Exception

        End Try
    End Sub

    Private Sub frmMain_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        'If RunWithLablinkService Then Application.Exit()
        'e.Cancel = True
        'WindowState = FormWindowState.Minimized
    End Sub

    Private Sub frmMain_SizeChanged(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.SizeChanged
        Try
            If gv_intWidth * gv_intSubSystemCount > SubSystemPanel.pnlBackGround.Height Then
                SubSystemPanel.ptbDown.Visible = True
                SubSystemPanel.ptbUp.Image = SubSystemPanel.imlUpDown.Images.Item(7)
                If SubSystemPanel.pnlBackGround.Controls(2).Top < 0 Then
                    AllowUp = True
                    SubSystemPanel.ptbUp.Visible = True
                Else
                    SubSystemPanel.ptbUp.Visible = False
                    AllowUp = False
                End If
                AllowDown = True
            Else
                If SubSystemPanel.pnlBackGround.Controls(2).Top < 0 Then
                    AllowUp = True
                    SubSystemPanel.ptbUp.Visible = True
                Else
                    SubSystemPanel.ptbUp.Visible = False
                    AllowUp = False
                End If
                SubSystemPanel.ptbDown.Visible = False
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub StatusBar1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles StatusBar1.DoubleClick
        If Not gv_bIsChecking Then
            gv_bCallCheckUpdate = True
            Dim threCheckUpdate As Thread
            threCheckUpdate = New Thread(AddressOf CheckLastestVersion)
            threCheckUpdate.Start()
        End If

    End Sub

#End Region

#Region "Private Method"

    'Load hình nền mặc định của ứng dụng
    'Thư mục chứa ảnh là Images
    'Tên file là Default.jpg, Default.bmp, Default.Gif
    Private Sub LoadDefaultBackGround()
        Try
            If File.Exists(Application.StartupPath & "\Images\Default.jpg") Then
                PictureBox1.Image = Image.FromFile(Application.StartupPath & "\Images\Default.jpg")
                Return
            ElseIf File.Exists(Application.StartupPath & "\Images\Default.Bmp") Then
                PictureBox1.Image = Image.FromFile(Application.StartupPath & "\Images\Default.Bmp")
                Return
            ElseIf File.Exists(Application.StartupPath & "\Images\Default.Gif") Then
                PictureBox1.Image = Image.FromFile(Application.StartupPath & "\Images\Default.Gif")
                Return
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Function LoginSystem(ByVal sender As Object, ByVal e As EventArgs) As Boolean
        'Dim clsUtil As New clsUtility
        'If gv_oSqlCnn Is Nothing Then
        '    Return False
        'End If
        'If Not clsUtil.CheckTable("TBL_MANAGEMENTUNIT") Then
        '    Dim svOForm As New Frm_AddBranch
        '    svOForm.ShowDialog()
        'End If
        'If Not clsUtil.CheckTable("TBL_MANAGEMENTUNIT", "PK_sBranchID=N'" & gv_sBranchID & "'") Then
        '    MessageBox.Show( _
        '        "Không tồn tại chi nhánh làm việc có mã: " & gv_sBranchID & _
        '        " trong CSDL. Đề nghị bạn chỉnh lại thông tin file cấu hình cho đúng", gv_sAnnouncement, _
        '        MessageBoxButtons.OK, MessageBoxIcon.Information)
        '    Return False
        'End If
        ' GetBranchInfo()
        Dim clsReg As New clsRegistry
        gv_bAnnouceWhenHavingLastestVersion = clsReg.GetReg(2, "DVC_COMPANY", "SYSMAN_APP", "AnnouceWhenHavingLastestVersion") <> "0"
        Dim svOLoginForm As New frmLogin
        svOLoginForm.ShowDialog()
        Try
            'Kiểm tra nếu đăng nhập thành công
            If gv_bLoginSuccess Then
                If gv_bAnnouceWhenHavingLastestVersion Then
                    CheckLastestVersion()
                    'Dim threCheckUpdate As Thread
                    'threCheckUpdate = New Thread(AddressOf CheckLastestVersion)
                    'threCheckUpdate.Start()
                End If
                Initialize()
                Application.DoEvents()
                ' SetSerialPort()
            Else
                Close()
            End If
            tbr.Buttons(1).Text = IIf(gv_sLanguageDisplay.ToUpper.Equals("VN"), "EN", "VN")
            tbr.Buttons(1).ToolTipText = IIf(gv_sLanguageDisplay.ToUpper.Equals("VN"), "Chuyển sang giao diện Tiếng Anh", "Chuyển sang giao diện Tiếng Việt")
            If gv_intWidth * gv_intSubSystemCount > SubSystemPanel.pnlBackGround.Height Then
                SubSystemPanel.ptbDown.Visible = True
                SubSystemPanel.ptbUp.Image = SubSystemPanel.imlUpDown.Images.Item(7)
                AllowUp = False
                AllowDown = True
            Else
                SubSystemPanel.ptbDown.Visible = False
            End If
            Return True
        Catch ex As Exception
            Cursor = Cursors.Arrow
            Return False
        End Try
    End Function

    Private Sub Initialize()
        _mvOmenu = New cls_BuildMenu(Me)
        _mnuMain = _mvOmenu.GetMainMenu
        ContextMenu = _mvOmenu.mv_ContextMenu
        Controls.Add(_mnuMain)
        LoadMainInfo()
    End Sub
    'Load Ip Adress vào (.)
    'Private Function GetIP() As String
    '    Dim strHostName As String = ""
    '    strHostName = System.Net.Dns.GetHostName()

    '    Dim ipEntry As IPHostEntry = System.Net.Dns.GetHostEntry(strHostName)

    '    Dim addr As IPAddress() = ipEntry.AddressList
    '    Dim strIp As String = addr(addr.Length - 1).ToString()

    '        Return strIp

    'End Function
    Public Shared Function localIPAddress() As String
        Dim host As IPHostEntry
        Dim localIP As String = ""
        host = Dns.GetHostEntry(Dns.GetHostName())

        For Each ip As IPAddress In host.AddressList
            localIP = ip.ToString()

            Dim temp As [String]() = localIP.Split("."c)
            If ip.AddressFamily = AddressFamily.InterNetwork Then
                localIP = ip.ToString()
                '    If ip.AddressFamily = AddressFamily.InterNetwork AndAlso temp(0) = "192" Or ip.AddressFamily = AddressFamily.InterNetwork AndAlso temp(0) = "10" Then
                Exit For
            Else
                localIP = Nothing
            End If
        Next
        Return localIP
    End Function

    Private Sub LoadMainInfo()
        'lablinkhelper.Utilities.SetControlProperty(StatusBar1.Panels(0), "Text", gv_sBranchName)
        StatusBar1.Panels(0).Text = gv_sBranchName
        StatusBar1.Panels(1).Text = "   Người dùng :  " & gv_sUID & "       " + "   Địa chỉ IP: " & localIPAddress() & "    "
        StatusBar1.Panels(2).Text = Now.ToShortDateString

    End Sub

    Private Shared Sub RecursiveChangeLanguageTbr(ByVal pvOMnuItem As MenuItem)
        Try
            For Each mnuItem As _MenuItem In pvOMnuItem.MenuItems
                If Not mnuItem.Tag Is Nothing Then
                    If gv_sLanguageDisplay.ToUpper = "VN" Then
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(0, Len(mnuItem.Tag.ToString.Substring(0, mnuItem.Tag.ToString.IndexOf("@"))))
                    Else
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1, Len(mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1)) - 2)
                    End If
                    RecursiveChangeLanguageTbr(mnuItem)
                End If
            Next
        Catch ex As Exception
        End Try
    End Sub

    Private Shared Sub RecursiveChangeLanguage(ByVal pvOMnuItem As MenuCommand)
        Try
            For Each mnuItem As MenuCommand In pvOMnuItem.MenuCommands
                If Not mnuItem.Tag Is Nothing Then
                    If gv_sLanguageDisplay.ToUpper = "VN" Then
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(0, Len(mnuItem.Tag.ToString.Substring(0, mnuItem.Tag.ToString.IndexOf("@"))))
                    Else
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1, Len(mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1)) - 2)
                    End If
                    RecursiveChangeLanguage(mnuItem)
                End If
            Next
        Catch ex As Exception
        End Try
    End Sub

    Private Sub ChangeLanguage()
        Try
            For Each mnuItem As MenuCommand In getMenuControl.MenuCommands
                If Not mnuItem.Tag Is Nothing And mnuItem.Tag <> "-111" Then
                    If gv_sLanguageDisplay.ToUpper = "VN" Then
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(0, Len(mnuItem.Tag.ToString.Substring(0, mnuItem.Tag.ToString.IndexOf("@"))))
                    Else
                        mnuItem.Text = mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1, Len(mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1)) - 2)
                    End If
                    RecursiveChangeLanguage(mnuItem)
                Else
                    RecursiveChangeLanguage(mnuItem)
                End If
            Next

            For Each btn As ToolBarButton In tbr.Buttons
                If Not btn.DropDownMenu Is Nothing Then
                    For Each mnuItem As _MenuItem In CType(btn, ToolBarBtn).DropDownMenu.MenuItems
                        If Not mnuItem.Tag Is Nothing And mnuItem.Tag <> "-111" Then
                            If gv_sLanguageDisplay.ToUpper = "VN" Then
                                mnuItem.Text = mnuItem.Tag.ToString.Substring(0, Len(mnuItem.Tag.ToString.Substring(0, mnuItem.Tag.ToString.IndexOf("@"))))
                            Else
                                mnuItem.Text = mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1, Len(mnuItem.Tag.ToString.Substring(mnuItem.Tag.ToString.IndexOf("@") + 1)) - 2)
                            End If
                            RecursiveChangeLanguageTbr(mnuItem)
                        Else
                            RecursiveChangeLanguageTbr(mnuItem)
                        End If
                    Next
                End If
            Next
            _mvOmenu.RebuildContextMenu()
            If gv_intPicOrder = 0 Then
                _mvOmenu.ChangeSubSystemLanguage()
            Else
                _mvOmenu.ChangeSubSystemLanguagePBT()
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Function getMenuControl() As MenuControl
        Dim m As New MenuControl
        Try
            For Each ctr As Control In Controls
                If ctr.GetType Is m.GetType Then
                    Return CType(ctr, MenuControl)
                End If
            Next
        Catch ex As Exception

        End Try
    End Function


#End Region

    ' Khởi động cổng COM
    'Private Sub SetSerialPort()
    '    Try
    '        Dim iCount, iPortNameId As Integer

    '        'Lấy về danh sách các cổng của máy
    '        _tblPortDevice = GetLocalPorts()

    '        'Nếu không có cổng nào trong DB  thì thông báo
    '        If _tblPortDevice Is Nothing Then
    '            MsgBox("Không lấy được cấu hình các cổng từ CSDL" & vbCrLf & "Kiểm tra lại file config.xml", vbOKOnly + MsgBoxStyle.Critical, "Thông báo")
    '        ElseIf _tblPortDevice.Rows.Count > 0 Then

    '            ReDim seryPorts(_tblPortDevice.Rows.Count - 1)
    '            ReDim gv_Result(3, _tblPortDevice.Rows.Count)
    '            If seryPorts.Length > 0 Then
    '                ReDim Preserve _arrStack(seryPorts.Length)
    '                ReDim Preserve _arrStackCi4100(seryPorts.Length)       'Belong to CI4100

    '                ReDim Preserve bStep(seryPorts.Length)
    '                ReDim Preserve bStep_CA550(seryPorts.Length)
    '                ReDim Preserve bStep_AU400(seryPorts.Length)
    '                ReDim Preserve bStep_AU640(seryPorts.Length)
    '                ReDim Preserve bStep_AU480(seryPorts.Length)
    '                ReDim Preserve bStep_CI4100(seryPorts.Length)

    '                Dim icnt As Byte
    '                For icnt = 0 To seryPorts.Length - 1
    '                    _arrStack(icnt).StackPointer = 0
    '                    _arrStackCi4100(icnt).StackPointer = 0
    '                    bStep(icnt) = 0
    '                    bStep_CA550(icnt) = 0
    '                    bStep_AU400(icnt) = 0
    '                    bStep_AU640(icnt) = 0
    '                    bStep_AU480(icnt) = 0
    '                    bStep_CI4100(icnt) = 0
    '                Next
    '            End If

    '            For iCount = 0 To _tblPortDevice.Rows.Count - 1

    '                For iPortNameId = 0 To seryPorts(iCount).GetPortNames.GetLength(0) - 1
    '                    If seryPorts(iCount).GetPortNames(iPortNameId) = _tblPortDevice.Rows(iCount).Item("Port_Name") Then
    '                        Try
    '                            seryPorts(iCount) = New SerialPort
    '                            Dim baudrate As Object = _tblPortDevice.Rows(iCount).Item("BaudRate")
    '                            seryPorts(iCount).BaudRate = baudrate
    '                            Dim portname As Object = _tblPortDevice.Rows(iCount).Item("Port_Name")
    '                            seryPorts(iCount).PortName = portname
    '                            Dim parity As Object = _tblPortDevice.Rows(iCount).Item("Parity")
    '                            seryPorts(iCount).Parity = parity
    '                            Dim databit As Object = _tblPortDevice.Rows(iCount).Item("DataBits")
    '                            seryPorts(iCount).DataBits = databit
    '                            Dim stopBits As Object = _tblPortDevice.Rows(iCount).Item("StopBits")
    '                            seryPorts(iCount).StopBits = stopBits
    '                            Dim dtrEnable As Object = _tblPortDevice.Rows(iCount).Item("DTR")
    '                            seryPorts(iCount).DtrEnable = dtrEnable
    '                            Dim rtsEnable As Object = _tblPortDevice.Rows(iCount).Item("RTS")
    '                            seryPorts(iCount).RtsEnable = rtsEnable

    '                            gv_Result(0, iCount) = _tblPortDevice.Rows(iCount).Item("TestType_ID")
    '                            gv_Result(1, iCount) = _tblPortDevice.Rows(iCount).Item("Port_ID")
    '                            gv_Result(3, iCount) = 0

    '                            AddHandler seryPorts(iCount).DataReceived, AddressOf DataRec

    '                            seryPorts(iCount).Open()
    '                            seryPorts(iCount).DiscardInBuffer()




    '                            Dim strDevice As String = _tblPortDevice.Rows(iCount).Item("Device_Name").ToString.ToUpper
    '                            gv_PortInUse.Add(seryPorts(iCount))
    '                            gv_PortDictionary.Add(seryPorts(iCount).PortName, strDevice)
    '                            gv_PortCount.Add(seryPorts(iCount).PortName, iCount)

    '                            'Ghi log lên textbox
    '                            Dim logstring As String
    '                            logstring = strDevice & ":" & portname
    '                            txtLog.Text = txtLog.Text & vbCrLf & logstring

    '                            Select Case strDevice
    '                                Case "ADVIA2120"
    '                                    Dim clsAdvia2120 As New Advia2120
    '                                    InitAdvia2120String = clsAdvia2120.CreateIMessage(MT)
    '                                    ADVIA2120PortIndex = iCount
    '                                    seryPorts(ADVIA2120PortIndex).Write(InitAdvia2120String)
    '                                    File.AppendAllText("C:\LOG\Advia2120_Log.txt", vbCrLf & Now.ToString & " COM:      " & InitAdvia2120String & vbCrLf & "ADVIA2120: ")
    '                                    advia2120_para(0) = gv_Result(0, iCount)
    '                                    advia2120_para(1) = gv_Result(1, iCount)
    '                                    blnInitAdvia2120 = True
    '                                    gv_Result(2, ADVIA2120PortIndex) = [String].Empty
    '                                    MT = &H30
    '                                    bStep(iCount) = 1
    '                                    ARTIMERADVIA2120 = New Timers.Timer(30000)
    '                                    ARTIMERADVIA2120.AutoReset = False
    '                                    ARTIMERADVIA2120.Enabled = True
    '                                    AddHandler ARTIMERADVIA2120.Elapsed, AddressOf OnTimerADVIA2120Elapsed
    '                                Case "COBAS400"
    '                                    COBAS_count = iCount
    '                                    seryPorts(COBAS_count).Write(clsCOBAS400.CreateSyncBlock)
    '                                    gv_Result(2, COBAS_count) = [String].Empty
    '                                    CurrentSC = 0
    '                                    ARTIMER = New Timers.Timer(10000)
    '                                    AddHandler ARTIMER.Elapsed, AddressOf OnTimerElapsed
    '                                Case "COBAS411"
    '                                    COBAS411_count = iCount
    '                                    gv_Result(2, COBAS411_count) = [String].Empty
    '                                    ARTIMERCOBAS411 = New Timers.Timer(1000)
    '                                    AddHandler ARTIMERCOBAS411.Elapsed, AddressOf OnTimerCOBAS411Elapsed
    '                                Case "CI4100"
    '                                    ARTIMER_ARCH = New Timers.Timer(100000)
    '                                    AddHandler ARTIMER_ARCH.Elapsed, AddressOf OnTimerARCHElapsed
    '                                Case "CI4100_KN"
    '                                    ARTIMER_ARCH = New Timers.Timer(100000)
    '                                    AddHandler ARTIMER_ARCH.Elapsed, AddressOf OnTimerARCHElapsed
    '                                Case "ISR1000"
    '                                    ARTIMER_ISR = New Timers.Timer(100000)
    '                                    AddHandler ARTIMER_ISR.Elapsed, AddressOf OnTimerISRElapsed
    '                                Case "GA400"
    '                                    ARTIMER_GA400 = New Timers.Timer(1000)
    '                                    AddHandler ARTIMER_GA400.Elapsed, AddressOf OnTimerElapsed_GA400
    '                                Case "XS1000I"
    '                                    xs1000i_para(0) = gv_Result(0, iCount)
    '                                    xs1000i_para(1) = gv_Result(1, iCount)

    '                            End Select
    '                        Catch ex As Exception
    '                            If File.Exists("ShowOpenPortError.txt") Then
    '                                Dim s As String = File.ReadAllText("ShowOpenPortError.txt")
    '                                If s.Trim = "" Then
    '                                    MessageBox.Show("Cổng " & _tblPortDevice.Rows(iCount).Item("Port_Name") & "không mở được!" & vbCrLf & ex.ToString)
    '                                End If
    '                            Else
    '                                MessageBox.Show("Cổng " & _tblPortDevice.Rows(iCount).Item("Port_Name") & "không mở được!" & vbCrLf & ex.ToString)
    '                            End If
    '                        End Try

    '                        Exit For
    '                    End If
    '                Next iPortNameId
    '            Next iCount
    '            Try
    '                If Not Directory.Exists("C:\LOG\") Then
    '                    Directory.CreateDirectory("C:\LOG\")
    '                End If
    '            Catch ex As Exception
    '                File.AppendAllText(Application.StartupPath, "Can't create the directory C:\LOG\ !")
    '            End Try

    '            Path_Centaur1 = "C:\LOG\Centaur1-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_Centaur2 = "C:\LOG\Centaur2-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_ELECSYS2010 = "C:\LOG\ELECSYS2010-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_Advia1650 = "C:\LOG\Advia1650-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_XT1800 = "C:\LOG\XT1800-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_XS100i = "C:\LOG\XS1000i-" & Now.ToString("yyyy-MM-dd") & ".txt"

    '            Path_AXSYM = "C:\LOG\AXSYM-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_CI4100 = "C:\LOG\CI4100-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_CI4100_KN = "C:\LOG\CI4100_KN-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_ISR1000 = "C:\LOG\ISR1000-" & Now.ToString("yyyy-MM-dd") & ".txt"

    '            Path_CA550 = "C:\LOG\CA550-" & Now.ToString("yyyy-MM-dd") & ".txt"

    '            Path_AU400 = "C:\LOG\AU400-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_AU640 = "C:\LOG\AU640-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_AU480 = "C:\LOG\AU480-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_Ruby = "C:\LOG\Ruby-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_CA500 = "C:\LOG\CA500-" & Now.ToString("yyyy-MM-dd") & ".txt"
    '            Path_GA400 = "C:\LOG\GA400-" & Now.ToString("yyyy-MM-dd") & ".txt"


    '        End If

    '        'For JCLV
    '        Dim fn As String = "C:\1111.txt"
    '        If File.Exists(fn) Then
    '            Me._clsDeviceconnection.spAxSYM(File.ReadAllLines(fn), 4, 1)
    '            MessageBox.Show("Import Success")
    '        End If

    '    Catch ex As Exception
    '        MsgBox("Có lỗi trong quá trình khởi động các cổng com", vbOK, "Thông báo lỗi")
    '        File.WriteAllText("C:\Lablink Startup Error.txt", ex.ToString())
    '    End Try
    'End Sub
   
    Sub LogOpen()
        File.AppendAllText("C:\LABLinkOpenCloseLog.txt", Now.ToString & ": Chương trình bật." & vbCrLf)
    End Sub

    Sub LogClose()
        File.AppendAllText("C:\LABLinkOpenCloseLog.txt", Now.ToString & ": Chương trình tắt." & vbCrLf & vbCrLf)
    End Sub

End Class